package cn.hy.nio.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class BioServer {

    public static void main(String[] args) throws Exception {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(8080));

        while (true) {
            SocketChannel socket = serverSocketChannel.accept();
            SocketHandle socketHandle = new SocketHandle(socket);
            new Thread(socketHandle).start();
        }
    }

    static class SocketHandle implements Runnable {

        private SocketChannel serverSocket;

        public SocketHandle(SocketChannel socketChannel) {
            this.serverSocket = socketChannel;
        }

        @Override
        public void run() {

            ByteBuffer buffer = ByteBuffer.allocate(1024);

            try {
                int num ;
                while (( num = serverSocket.read(buffer))  > 0) {

                    buffer.flip();
                    byte[] bytes = new byte[num];

                    buffer.get(bytes);

                    String content = new String(bytes, StandardCharsets.UTF_8);

                    System.out.println(content);

                    ByteBuffer writeBuffer = ByteBuffer.wrap(("我已经收到你的请求 内容是:" + content).getBytes(StandardCharsets.UTF_8));

                    serverSocket.write(writeBuffer);

                    buffer.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
